package cn.lixin.controller;

import cn.lixin.to.UserTo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@EnableCircuitBreaker
public class OrderController {

    // 在启动类中配置bean才可用
    @Autowired
    private RestTemplate restTemplate ;

    @GetMapping("/order/{id}")
    @LoadBalanced // 负载均衡
    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public UserTo getById(@PathVariable("id") Long id){
//        String url = "http://localhost:1021/user/" + id;
        String url = "http://USER-SERVER/user/" + id; //底层会通过服务发现的方式使用Ribbin进行负载均衡调用
        return restTemplate.getForObject(url,UserTo.class);
    }

    // 负载均衡算法
    @Bean
    public RandomRule randomRule(){
        return new RandomRule();
    }
    public UserTo fallbackMethod(@PathVariable("id") Long id){
//        String url = "http://localhost:1021/user/" + id;
        String url = "http://USER-SERVER/user/" + id; //底层会通过服务发现的方式使用Ribbin进行负载均衡调用
        return new UserTo(-1L,"服务异常by order");
    }

}

